import { Tooltip, Tag, Modal, message, Spin, Badge } from 'antd';
import type { Settings as ProSettings } from '@ant-design/pro-layout';
import { ExclamationCircleFilled, QuestionCircleOutlined, SketchOutlined } from '@ant-design/icons';
import React, { useEffect, useState } from 'react';
import type { ConnectProps } from 'umi';
import { history, connect, SelectLang } from 'umi';
import type { ConnectState } from '@/models/connect';
import Avatar from './AvatarDropdown';
import HeaderSearch from '../HeaderSearch';
import styles from './index.less';
import AuthPrd from './AuthPrd';
import request from 'umi-request';

export type GlobalHeaderRightProps = {
  theme?: ProSettings['navTheme'] | 'realDark';
} & Partial<ConnectProps> &
  Partial<ProSettings>;

const ENVTagColor = {
  dev: 'orange',
  test: 'green',
  pre: '#87d068',
};
const { confirm } = Modal;
const GlobalHeaderRight: React.FC<GlobalHeaderRightProps> = (props: any) => {
  const { theme, layout, currentTenant } = props;
  let className = styles.right;

  if (theme === 'dark' && layout === 'top') {
    className = `${styles.right}  ${styles.dark}`;
  }
  const [visible, setVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [isNew, seIsNew] = useState<boolean>(false);
  const [isUpdate, seIsUpdate] = useState<boolean>(false);
  const [newVersion, setNewVersion] = useState<string>('');
  const inValid = new Date(currentTenant.endDate) < new Date();
  const checkNewVersion = () => {
    request('/api/services/app/SysConfig/CheckNewVersion', {
      method: 'POST',
    }).then((response) => {
      if (response.result && response.result.data) {
        seIsNew(true);
        confirm({
          title: '系统提示',
          icon: <ExclamationCircleFilled />,
          content: '有新版本' + response.result.message + '，是否更新？',
          onOk() {
            updateSys();
          },
          onCancel() {
            seIsUpdate(false);
            return;
          },
        });
      } else {
        message.success('当前系统已是最新版！');
      }
    });
  };
  const updateSys = () => {
    setLoading(true);
    request('/api/services/app/SysConfig/UpdateSysAsync', {
      method: 'PUT',
    }).then((response) => {
      if (response.success) {
        seIsNew(false);
        seIsUpdate(true);
        setNewVersion(response.result);
        message.success('系统更新成功！');
      }
      setLoading(false);
    });
  };
  useEffect(() => {
    checkNewVersion();
    if (inValid) {
      setVisible(true);
    }
  }, []);
  return (
    <div className={className}>
      {/* <Tooltip title="恩尔普云应用市场">
        <a onClick={() => history.push('/Market')}>
          <Tag color="red" icon={<SketchOutlined />}>
            云市场
          </Tag>
        </a>
      </Tooltip> */}
      <Tooltip title="点我检查最新版">
        <Spin size="small" spinning={loading}>
          <a onClick={() => checkNewVersion()}>
            <Badge dot={isNew}>
              <Tag color="processing">
                企业版 V{isUpdate ? newVersion : props?.currentConfig?.version}
              </Tag>
            </Badge>
          </a>
        </Spin>
      </Tooltip>
      <Tooltip title="在线购买授权码">
        <a onClick={() => setVisible(true)}>
          <Tag color={inValid ? '#cd201f' : '#87d068'}>{inValid ? '授权' : '已授权'}</Tag>
        </a>
      </Tooltip>
      <HeaderSearch
        className={`${styles.action} ${styles.search}`}
        placeholder="Site Search"
        defaultValue="在线文档"
        options={[
          {
            label: (
              <a
                href="https://www.yuque.com/books/share/ac4c0470-4b8c-406e-9709-0045ba7703ce"
                target="_blank"
              >
                在线文档
              </a>
            ),
            value: '在线培训',
          },
          {
            label: (
              <a href="http://cms.oplug.cn" target="_blank">
                编码工具
              </a>
            ),
            value: '编码工具',
          },
          {
            label: (
              <a href="http://cms.oplug.cn" target="_blank">
                业务报表
              </a>
            ),
            value: '业务报表',
          },
        ]}
        // onSearch={value => {
        //   //console.log('input', value);
        // }}
      />
      <Tooltip title="在线帮助">
        <a
          style={{
            color: 'inherit',
          }}
          target="_blank"
          href="https://www.yuque.com/books/share/ac4c0470-4b8c-406e-9709-0045ba7703ce"
          rel="noopener noreferrer"
          className={styles.action}
        >
          <QuestionCircleOutlined />
        </a>
      </Tooltip>

      <Avatar />
      {REACT_APP_ENV && (
        <span>
          <Tag color={ENVTagColor[REACT_APP_ENV]}>{REACT_APP_ENV}</Tag>
        </span>
      )}
      <SelectLang className={styles.action} />
      <Modal
        title={<b>产品授权</b>}
        visible={visible}
        onOk={() => setVisible(false)}
        onCancel={() => setVisible(false)}
        footer={null}
        destroyOnClose={true}
        width={550}
      >
        <AuthPrd />
      </Modal>
    </div>
  );
};

export default connect(({ settings, user }: ConnectState) => ({
  theme: settings.navTheme,
  layout: settings.layout,
  currentTenant: user.currentTenant,
  currentConfig: user.currentConfig,
}))(GlobalHeaderRight);
